package engine.scene;

import engine.render.SoundBuffer;
import engine.util.SoundUtil;
import math.vector.vec3f;
import static org.lwjgl.openal.AL10.*;

public class SoundSource
{
    
    private int soundSourceID;
    
    private SoundBuffer soundBuffer;
    
    private float soundPitch;
    //<editor-fold defaultstate="collapsed" desc="setPitch">
    public void setPitch(float pitch)
    {
        this.soundPitch = pitch;
    }
    //</editor-fold>
    
    private float soundGain;
    //<editor-fold defaultstate="collapsed" desc="setGain">
    public void setGain(float gain)
    {
        this.soundGain = gain;
    }
    //</editor-fold>
    
    private vec3f soundPos;
    //<editor-fold defaultstate="collapsed" desc="setPosition">
    public void setPosition(vec3f position)
    {
        this.soundPos.setTo(position);
    }
    //</editor-fold>
    
    private vec3f soundVel;
    //<editor-fold defaultstate="collapsed" desc="setVelocity">
    public void setVelocity(vec3f velocity)
    {
        this.soundVel.setTo(velocity);
    }
    //</editor-fold>
    
    private boolean soundLooping;
    //<editor-fold defaultstate="collapsed" desc="setLooping">
    public void setLooping(boolean looping)
    {
        this.soundLooping = looping;
    }
    //</editor-fold>
    
    public SoundSource(SoundBuffer soundBuffer)
    {
        this.soundSourceID = SoundUtil.get().genALSoundSource();
        
        this.soundBuffer = soundBuffer;
        this.soundPitch = 1.0f;
        this.soundGain = 1.0f;
        this.soundPos = new vec3f();
        this.soundVel = new vec3f();
        this.soundLooping = false;
    }
    
    public void bind()
    {
        int isLooping = (this.soundLooping ? AL_TRUE : AL_FALSE);
        
        alSourcei(this.soundSourceID, AL_BUFFER, this.soundBuffer.getSoundBufferID());
        alSourcef(this.soundSourceID, AL_PITCH, this.soundPitch);
        alSourcef(this.soundSourceID, AL_GAIN, this.soundGain);
        alSource3f(this.soundSourceID, AL_POSITION, 
            this.soundPos.x, 
            this.soundPos.y, 
            this.soundPos.z
        );
        alSource3f(this.soundSourceID, AL_VELOCITY, 
            this.soundVel.x, 
            this.soundVel.y, 
            this.soundVel.z
        );
        alSourcei(this.soundSourceID, AL_LOOPING, isLooping);
    }
    
    public void destroy()
    {
        alDeleteSources(this.soundSourceID);
        this.soundSourceID = -1;
        this.soundBuffer = null;
        this.soundPitch = 0.0f;
        this.soundGain = 0.0f;
        this.soundPos = null;
        this.soundVel = null;
        this.soundLooping = false;
    }
    
}
